using System;
using System.Web;
using System.IO;


namespace Blazing.Cms.Util
{
	/// <summary>
	/// Helps save uploaded files to the correct directory
	/// </summary>
	public class UploadHelper
	{
		public UploadHelper()
		{
			
		}

		public static string ConvertString(string str)
		{
			string[] badChars = new string[] {"\'", " ", "\\",","};
			string[] repChars = new string[] {""  , "-", "", ""};
            string final = str;
			for(int i=0;i<badChars.Length;i++)
			{
                final = final.Replace(badChars[i], repChars[i]);
			}
			return final;
		}

		public static void SaveImage(string SavePath, System.Web.UI.HtmlControls.HtmlInputFile img)
		{
			if (!System.IO.Directory.Exists(SavePath))
				System.IO.Directory.CreateDirectory(SavePath);
				
			string filename = UploadHelper.ConvertString(Path.GetFileName(img.PostedFile.FileName));
			img.PostedFile.SaveAs(SavePath + "/" + filename.ToLower());
		}

		/// <summary>
		/// Maps the physical path where a newly uploaded image is to be saved.
		/// </summary>
		/// <param name="objName">Name of the Building/Product/Contact the image is for</param>
		/// <param name="imageTypePath">The path from the image type</param>
		/// <param name="imageFileName">File name of the image</param>
		/// <param name="server">Server context where the path is to be mapped</param>
		/// <returns></returns>
		public static string MapImagePath(string objName, string imageTypePath, System.Web.HttpServerUtility server)
		{
			string SavePath = server.MapPath(ConvertString(imageTypePath.ToLower()));
			SavePath += ConvertString("/" + objName.ToLower());
			return SavePath;
		}

	}
}
